import weaponData from '../../resources/config/weapons.json';
import ammoData from '../../resources/config/ammo.json';
import { WeaponStats, AmmoDefinition, AmmoType } from '../shared';

const weaponCache = new Map<string, WeaponStats>();
const ammoCache = new Map<AmmoType, AmmoDefinition>();

function ensureWeaponCache() {
  if (weaponCache.size > 0) {
    return;
  }
  Object.entries(weaponData as Record<string, any>).forEach(([id, raw]) => {
    weaponCache.set(id, {
      id,
      name: raw.name ?? id,
      ammoType: raw.ammoType,
      roundsPerSecond: raw.roundsPerSecond,
      baseDamage: raw.baseDamage,
      effectiveRange: raw.effectiveRange,
      spread: raw.spread,
      pellets: raw.pellets ?? 1,
      pierce: raw.pierce ?? 0,
      critChance: raw.critChance,
      critMultiplier: raw.critMultiplier,
      magazineSize: raw.magazineSize,
      reloadTime: raw.reloadTime,
      attachments: {
        spreadBonus: raw.attachments?.spreadBonus ?? 0,
        recoilBonus: raw.attachments?.recoilBonus ?? 0,
        laserAssist: raw.attachments?.laserAssist ?? false,
        penetrationBonus: raw.attachments?.penetrationBonus ?? 0,
        critBonus: raw.attachments?.critBonus ?? 0,
      },
    });
  });
}

function ensureAmmoCache() {
  if (ammoCache.size > 0) {
    return;
  }
  Object.entries(ammoData as Record<string, any>).forEach(([id, raw]) => {
    ammoCache.set(id as AmmoType, {
      id: id as AmmoType,
      category: raw.category,
      stack: raw.stack,
      magazineBase: raw.magazineBase,
    });
  });
}

export function getWeaponStats(id: string): WeaponStats | undefined {
  ensureWeaponCache();
  return weaponCache.get(id);
}

export function getAmmoDefinition(type: AmmoType): AmmoDefinition | undefined {
  ensureAmmoCache();
  return ammoCache.get(type);
}


